<template>
  <div >
    <el-upload v-if="isUpload"
               class="upload-demo"
               ref="elUpload"
               action="http://up-z1.qiniup.com"
               :data="qnFileData"
               :on-preview="handlePreview"
               :on-remove="handleRemove"
               :before-remove="beforeRemove"
               :limit="maxFileLength"
               :on-exceed="handleExceed"
               :before-upload="beforeAvatarUpload"
               :on-success="handleAvatarSuccess"
               :file-list="fileList"
    >
      <!-- multiple 多选 -->
      <el-button size="small" type="primary" v-if="isUpload"
      >点击上传</el-button
      ></el-upload
    >
    <span v-else class="file-list">
    <div class="file-item" v-for="item of fileList" :key="item.Key">
      <a :href="item.value" target="_blank">{{item.name}}</a>
    </div>
  </span>
  </div>
</template>
<script>
    import { downloadFile } from "@/utils/downloadFile";
    export default {
        name: "uploadele",
        props: {
            maxFileLength: { type: Number, default: 3 }, //最大上传文件数量
            fileArr: { type: Array, default: () =>[] },
            isUpload: { type: Boolean, default: true }, // 是否上传模式
            clsListBoolean: { type: Boolean }, //是否清空
        },
        watch: {
            clsListBoolean(newVal) {
                if (newVal) {
                    this.fileList = [];
                    this.fileListSubmit = [];
                    this.$refs['elUpload']?.clearFiles();
                    this.$emit("clsRefresh", false);
                }
            },
            fileArr(newVal){
                if (this.fileArr&&this.fileArr.length) {
                    let fileList = [], fileSubmitList = [];
                    let fileListData = this.fileArr;
                    fileListData.forEach((item) => {
                        let itemData = {
                            name: item.Key,
                            value: item.Value + "?attname=" + item.Key,
                        };
                        let submitData = {
                            Key: item.Key,
                            Value: item.Value,
                        };
                        fileList.push(itemData);
                        fileSubmitList.push(submitData);
                    });
                    this.fileList.splice(0,this.fileList.length,...fileList);
                    this.fileListSubmit = fileSubmitList;
                } else {
                    this.fileList.splice(0,this.fileList.length)
                    this.fileListSubmit.splice(0,this.fileListSubmit.length);
                    this.$refs['elUpload']?.clearFiles();
                }
            }
        },
        data() {
            return {
                QNSrcHeader: process.env.VUE_APP_QINIU_URL,
                qnFileData: {
                    token: "",
                },
                fileDate:[],
                fileList: [],
                fileListSubmit: [], // 提交的数据
                FileType: "", //文件类型
            };
        },
        methods: {
            handlePreview(file) {
                //下载
                console.log(file);
                downloadFile(file.value);
            },
            handleRemove(file, fileList) {
                console.log(123)
                //附件删除
                let fileListSubmit = this.fileListSubmit;
                let fileNameList = fileListSubmit.map((item) => item.Value);
                let spliceIndex = fileNameList.indexOf(file.name);
                fileListSubmit.splice(spliceIndex, 1);
                this.fileListSubmit = fileListSubmit;
                this.fileList.splice(0,this.fileList.length,...fileList);
                this.fileArr.splice(0,this.fileArr.length)
                for(var item of this.fileList){
                    this.fileArr.push({
                        Key:item.name,
                        Value:item.value.split('?')[0]
                    })
                }
                //this.backDataMehods();
            },
            beforeRemove(file, fileList) {
                //文件删除前确认
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            handleExceed(files, fileList) {
                this.$message.warning(
                    `当前限制选择 ${this.maxFileLength} 个文件，本次选择了 ${
                        files.length
                    } 个文件，共选择了 ${files.length + fileList.length} 个文件`
                );
            },
            handleAvatarSuccess(res, file) {
                this.fileList.push({
                    name: this.FileType,
                    value: this.QNSrcHeader + res.hash + "?attname=" + this.FileType,
                });
                this.fileListSubmit.push({
                    Value: this.QNSrcHeader + res.hash,
                    Key: this.FileType,
                });
                this.fileArr.splice(0,this.fileArr.length)
                for(var item of this.fileList){
                    this.fileArr.push({
                        Key:item.name,
                        Value:item.value.split('?')[0]
                    })
                }
                //this.backDataMehods();
            },
            QNTokenRequestFun() {
                return this.$api.GET_QINIU_TOKEN().then((res) => {
                    if (res.code == 200) this.qnFileData.token = res.data;
                });
            },
            async beforeAvatarUpload(file) {
                // 文件上传前
                // this.qnFileData.key = file.name;
                var FileExt = file.name.replace(/.+\./, "");
                this.FileType = file.name;
                this.fileDate = file
                await this.QNTokenRequestFun();
            },
            backDataMehods() {
                this.$emit("update:toFarUpload", this.fileListSubmit);
            }
        },
        created() {
            console.log(this.fileArr);
            if(!this.fileArr){
                this.fileArr=[]
            }
            if (this.fileArr.length) {
                let fileList = [], fileSubmitList = [];
                let fileListData = this.fileArr;
                fileListData.forEach((item) => {
                    let itemData = {
                        name: item.Key,
                        value: item.Value + "?attname=" + item.Key,
                    };
                    let submitData = {
                        Key: item.Key,
                        Value: item.Value,
                    };
                    fileList.push(itemData);
                    fileSubmitList.push(submitData);
                });
                this.fileList.splice(0,this.fileList.length,...fileList);
                this.fileListSubmit = fileSubmitList;
            }
        },
    };
</script>
<style lang="scss" scoped>
  @import "@/styles/variables.scss";
  .file-list{
    .file-item{
      color:$main-color;
      padding-bottom: $block-y;
      a{
        color:$main-color;
      }
    }
    .file-item:last-child{
      padding-bottom: 0;
    }
  }
</style>
